// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    switch (request.action) {
        case 'fullPageScreenshot':
            captureFullPage();
            break;
        case 'screenshot':
            captureVisiblePage();
            break;
        case 'savePDF':
            saveToPDF();
            break;
        case 'saveWord':
            saveToWord();
            break;
        case 'saveExcel':
            saveToExcel();
            break;
    }
});

// 长截图功能
async function captureFullPage() {
    try {
        const canvas = await html2canvas(document.documentElement, {
            allowTaint: true,
            useCORS: true,
            scrollY: 0,
            height: Math.max(
                document.documentElement.clientHeight,
                document.documentElement.scrollHeight
            )
        });
        
        const imageData = canvas.toDataURL('image/png');
        chrome.runtime.sendMessage({
            type: 'download',
            data: imageData,
            filename: '长截图.png'
        });
    } catch (error) {
        console.error('长截图失败:', error);
    }
}

// 可视区域截图
async function captureVisiblePage() {
    try {
        const canvas = await html2canvas(document.documentElement, {
            allowTaint: true,
            useCORS: true,
            scrollY: window.scrollY,
            height: window.innerHeight,
            windowHeight: window.innerHeight
        });
        
        const imageData = canvas.toDataURL('image/png');
        chrome.runtime.sendMessage({
            type: 'download',
            data: imageData,
            filename: '截图.png'
        });
    } catch (error) {
        console.error('截图失败:', error);
    }
}

// 保存为PDF（优化版）
async function saveToPDF() {
    try {
        const { jsPDF } = window.jspdf;
        
        // 使用html2canvas捕获页面内容
        const canvas = await html2canvas(document.documentElement, {
            allowTaint: true,
            useCORS: true,
            scale: 2, // 提高清晰度
            logging: false,
            windowWidth: document.documentElement.scrollWidth,
            windowHeight: document.documentElement.scrollHeight
        });

        // 计算PDF尺寸（保持宽高比）
        const imgWidth = 210; // A4纸的宽度（mm）
        const pageHeight = 297; // A4纸的高度（mm）
        const imgHeight = canvas.height * imgWidth / canvas.width;
        const pageCount = Math.ceil(imgHeight / pageHeight);

        // 创建PDF文档
        const doc = new jsPDF({
            orientation: imgHeight > imgWidth ? 'portrait' : 'landscape',
            unit: 'mm',
            format: 'a4',
        });

        // 设置中文字体支持
        doc.addFont('https://fonts.googleapis.com/css2?family=Noto+Sans+SC', 'Noto Sans SC', 'normal');
        doc.setFont('Noto Sans SC');

        // 添加页面内容
        let heightLeft = imgHeight;
        let position = 0;

        for (let i = 0; i < pageCount; i++) {
            if (i > 0) {
                doc.addPage();
            }

            const contentWidth = canvas.width;
            const contentHeight = Math.min(canvas.height - position, (pageHeight * canvas.width) / imgWidth);

            // 将canvas内容添加到PDF
            const pageData = canvas.getContext('2d').getImageData(
                0,
                position,
                contentWidth,
                contentHeight
            );

            const pageCanvas = document.createElement('canvas');
            pageCanvas.width = contentWidth;
            pageCanvas.height = contentHeight;
            pageCanvas.getContext('2d').putImageData(pageData, 0, 0);

            const imgData = pageCanvas.toDataURL('image/jpeg', 1.0);
            doc.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight);

            heightLeft -= pageHeight;
            position += contentHeight;
        }

        const pdfData = doc.output('datauristring');
        chrome.runtime.sendMessage({
            type: 'download',
            data: pdfData,
            filename: `${document.title || '网页内容'}.pdf`
        });
    } catch (error) {
        console.error('PDF生成失败:', error);
        alert('PDF生成失败，请稍后重试');
    }
}

// 保存为Word（优化版）
async function saveToWord() {
    try {
        // 获取页面样式
        const styles = Array.from(document.styleSheets)
            .map(sheet => {
                try {
                    return Array.from(sheet.cssRules)
                        .map(rule => rule.cssText)
                        .join('\n');
                } catch (e) {
                    return '';
                }
            })
            .join('\n');

        // 获取页面内容，保留图片
        const content = document.body.innerHTML;
        
        // 处理图片路径为绝对路径
        const processedContent = content.replace(
            /<img[^>]+src="([^"]+)"[^>]*>/g,
            (match, src) => {
                const absoluteSrc = new URL(src, window.location.href).href;
                return match.replace(src, absoluteSrc);
            }
        );

        // 创建完整的HTML文档
        const htmlContent = `
            <!DOCTYPE html>
            <html>
                <head>
                    <meta charset="UTF-8">
                    <title>${document.title || '网页内容'}</title>
                    <style>
                        ${styles}
                        body {
                            font-family: "Microsoft YaHei", Arial, sans-serif;
                            line-height: 1.6;
                            margin: 20px;
                        }
                        img {
                            max-width: 100%;
                            height: auto;
                        }
                        table {
                            border-collapse: collapse;
                            width: 100%;
                        }
                        td, th {
                            border: 1px solid #ddd;
                            padding: 8px;
                        }
                    </style>
                </head>
                <body>
                    ${processedContent}
                </body>
            </html>
        `;

        // 创建Blob对象
        const blob = new Blob([htmlContent], {
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        });

        const wordData = URL.createObjectURL(blob);
        chrome.runtime.sendMessage({
            type: 'download',
            data: wordData,
            filename: `${document.title || '网页内容'}.docx`
        });
    } catch (error) {
        console.error('Word文档生成失败:', error);
        alert('Word文档生成失败，请稍后重试');
    }
}

// 保存为Excel
function saveToExcel() {
    try {
        let data = [];
        // 获取所有表格
        const tables = document.getElementsByTagName('table');
        if (tables.length > 0) {
            // 处理第一个表格
            const table = tables[0];
            const rows = table.rows;
            for (let i = 0; i < rows.length; i++) {
                const row = rows[i];
                const rowData = [];
                for (let j = 0; j < row.cells.length; j++) {
                    rowData.push(row.cells[j].innerText);
                }
                data.push(rowData.join('\t'));
            }
        } else {
            // 如果没有表格，尝试提取结构化数据
            const content = document.body.innerText;
            data = content.split('\n').map(line => line.trim()).filter(line => line);
        }
        
        const blob = new Blob([data.join('\n')], { type: 'application/vnd.ms-excel' });
        const excelData = URL.createObjectURL(blob);
        chrome.runtime.sendMessage({
            type: 'download',
            data: excelData,
            filename: '网页内容.xls'
        });
    } catch (error) {
        console.error('Excel文件生成失败:', error);
    }
} 